package omdb;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import UrlExtractor.*;
/**
 * this class gives omdb api response of queries same them into files.
 * @author chenji
 *
 */
public class Omdb {
public static String getMovieInfo(String qry) throws Exception{
	String url = "http://www.omdbapi.com/?" + qry;
	//System.out.println(url);
	URL obj = new URL(url);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	con.setRequestMethod("GET");
	con.setRequestProperty("User-Agent", "Mozilla/5.0");

	BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
	String inputLine;
	StringBuffer response = new StringBuffer();
	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();
	con.disconnect();
	return response.toString();
}
public static void main(String[] args) {
	try {
		List<String> idList = GetMovieNames.readFromFile("movies");
		File file = new File("omdb");
		FileOutputStream out = new FileOutputStream(file);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
		for (String id : idList) {
			String url = "http://www.omdbapi.com/?i=" + id;
			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("User-Agent", "Mozilla/5.0");

			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			con.disconnect();
			writer.write(response.toString().substring(1, response.length() - 1) + "\n");
		}
		writer.flush();
		writer.close();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}
